package com.atguigu.gmall.user.controller;

import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.model.user.UserInfo;
import com.atguigu.gmall.user.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author BrookPeng
 * @Date 2020/12/2 18:34
 * @Version 1.0
 */
@RestController
@RequestMapping("/api/user/passport")
public class UserApiController {

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private RedisTemplate redisTemplate;

    // 提交登陆表单
    @PostMapping("/login")
    public Result login(@RequestBody UserInfo userInfo) {

        if (null == userInfo || "".equals(userInfo.getLoginName().trim())) {
            return Result.fail().message("用户名不能为空");
        }
        if (null == userInfo || "".equals(userInfo.getPasswd().trim())) {
            return Result.fail().message("密码不能为空");
        }

        // 验证用户名密码是否正确
        userInfo = userInfoService.login(userInfo);
        if (userInfo != null) {
            // 准备token
            Map map = new HashMap<>();
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            map.put("token", uuid);
            map.put("nickName", userInfo.getNickName());

            redisTemplate.opsForValue().set(RedisConst.USER_LOGIN_KEY_PREFIX + uuid, userInfo, RedisConst.USERKEY_TIMEOUT, TimeUnit.SECONDS);

            return Result.ok(map);
        }
        return Result.fail().message("用户名或密码不正确");
    }

    // 退出登录
    @GetMapping("/logout")
    public Result logout(HttpServletRequest request) {

        String token = request.getHeader("token");
        // 删除缓存中的token
        if (redisTemplate.hasKey(RedisConst.USER_LOGIN_KEY_PREFIX + token)) {
            redisTemplate.delete(RedisConst.USER_LOGIN_KEY_PREFIX + token);
        }
        return Result.ok().message("登出成功");
    }

    // 查询用户地址
    @GetMapping("/findUserAddressList")
    public List<UserAddress> findUserAddressList() {

        return userInfoService.findUserAddressList();
    }
}
